package com.API.dal.providers;

import com.API.dal.entities.Location;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
@Scope(value = "request",  proxyMode = ScopedProxyMode.INTERFACES)
public class LocationProviderImp implements LocationProvider {

    @Autowired
    SessionFactory sessionFactory;

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public List<Location> getLocations() {
        List<Location> locations;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Location l");
        locations = query.list();
        return locations;
    }

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public Location getLocationByName(String name) {
        Location location;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Location l where l.name = '" + name + "'");
        location = (Location) query.uniqueResult();
        return location;
    }

    @Override
    @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
    public Location getLocationById(int id) {
        Location location;
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Location l where l.id = " + id);
        location = (Location) query.uniqueResult();
        return location;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public void addLocation(Location location) {
        Session session = sessionFactory.getCurrentSession();
        session.save(location);
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public void updateLocation(Location location) {
        Session session = sessionFactory.getCurrentSession();
        session.update(location);
    }
}
